﻿// Fill out your copyright notice in the Description page of Project Settings.


#include "CharacterZD/BTService/BTService_MonsterFindTarget.h"

#include "BehaviorTree/BlackboardComponent.h"
#include "CharacterZD/Core/MonsterAIController.h"
#include "CharacterZD/Core/RuleCharacterZD.h"
#include "GameFramework/CharacterMovementComponent.h"

void UBTService_MonsterFindTarget::TickNode(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory, float DeltaSeconds)
{
	Super::TickNode(OwnerComp, NodeMemory, DeltaSeconds);

	AMonsterAIController* MonsterAIController = Cast<AMonsterAIController>(OwnerComp.GetOwner());
	UBlackboardComponent* MyBlackBoard = OwnerComp.GetBlackboardComponent();
	if (MonsterAIController && MyBlackBoard)
	{
		ARuleCharacterZD* NewTarget = Cast<ARuleCharacterZD>(MonsterAIController->FindTarget());
		if (NewTarget && NewTarget != Target)
		{
			if (ARuleCharacterZD* MonsterSelf = Cast<ARuleCharacterZD>(MonsterAIController->GetPawn()))
			{
				MonsterSelf->GetCharacterMovement()->StopMovementImmediately();
			}
			Target = NewTarget;
		}

		if (Target.IsValid() && Target->IsActive())
		{
			FVector NewTargetV = MonsterAIController->GetPawn()->GetActorLocation() - Target.Get()->GetActorLocation();
			NewTargetV.Normalize();
			const FVector CurrentLocation = NewTargetV * 800.f + Target.Get()->GetActorLocation();
			
			MyBlackBoard->SetValueAsObject(BlackboardKey_Target.SelectedKeyName, Target.Get());
			MyBlackBoard->SetValueAsVector(BlackboardKey_TargetLocation.SelectedKeyName, CurrentLocation);
		}
		else
		{
			MyBlackBoard->SetValueAsObject(BlackboardKey_Target.SelectedKeyName, nullptr);
			MyBlackBoard->SetValueAsVector(BlackboardKey_TargetLocation.SelectedKeyName, FVector::Zero());
		}
	}

	if (Target.IsValid())
	{
		FVector MyLocation = MonsterAIController->GetPawn()->GetActorLocation();
		FVector TMDistance = MyLocation - Target->GetActorLocation();
		if (TMDistance.Size() > 2200)
		{
			if(ARuleCharacterZD* MonsterAI = Cast<ARuleCharacterZD>(MonsterAIController->GetPawn()))
			{
				MonsterAI->bAttack = false;
			}
		}

		MyBlackBoard->SetValueAsFloat(BlackboardKey_Distance.SelectedKeyName, TMDistance.Size());
	}
	else
	{
		MyBlackBoard->SetValueAsFloat(BlackboardKey_Distance.SelectedKeyName, 0.0f);
	}
	
}

void UBTService_MonsterFindTarget::OnGameplayTaskInitialized(UGameplayTask& Task)
{
	Super::OnGameplayTaskInitialized(Task);
}

void UBTService_MonsterFindTarget::OnGameplayTaskActivated(UGameplayTask& Task)
{
	Super::OnGameplayTaskActivated(Task);
}

void UBTService_MonsterFindTarget::OnGameplayTaskDeactivated(UGameplayTask& Task)
{
	Super::OnGameplayTaskDeactivated(Task);
}
